import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.input.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import util.JarUtils;
import util.WindowCmdCtrl;
import view.HintTextArea;

import java.awt.*;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Main extends Application {

    private final Button changeBtn = new Button("开始签名(Ctrl+Enter)");

    private final HintTextArea inputTv = new HintTextArea();
    private final TextArea outputTv = new TextArea();
    private final Label mVersionLabel = new Label("版本号:2022.07.05 015845");

    private final String mLocalPath = JarUtils.getLocalDir(Main.class,"UTF-8")+"/bin/";
    private String mSelectPath = "";

    private final List<String> mChoiceList = new ArrayList<>();
    private final ChoiceBox<String> mChoiceBox = new ChoiceBox<>();

    @Override
    public void start(Stage stage) {
        AnchorPane root = new AnchorPane();

        initTv(root);
        initButton(root);

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.initStyle(StageStyle.DECORATED);
        stage.setTitle("APK系统签名工具");
        stage.setHeight(300);
        stage.setWidth(550);
        stage.show();

        //监听键盘Ctrl+Enter，执行转换
        KeyCombination kccb = new KeyCodeCombination(KeyCode.ENTER,KeyCombination.CONTROL_DOWN);
        scene.getAccelerators().put(kccb, this::input2output);

        File dir =  new File(mLocalPath);
        if (!dir.exists()){
            dir.mkdirs();
        }

        File[] list = new File(mLocalPath).listFiles(new FileFilter() {
            @Override
            public boolean accept(File f) {
                return f.isDirectory();
            }
        });

        if (list == null||list.length == 0){
            outputTv.setText("没有找到签名文件");
        }else{
            for (File f:list){
                mChoiceList.add(f.getName());
            }

            mChoiceBox.getItems().addAll(mChoiceList);
            mChoiceBox.getSelectionModel().select(0);
        }
    }

    private void initButton(AnchorPane root) {
        AnchorPane.setTopAnchor(changeBtn,125.0);
        AnchorPane.setRightAnchor(changeBtn,10.0);

        changeBtn.setOnMouseClicked(event -> input2output());
        root.getChildren().addAll(changeBtn);
    }

    private void input2output() {
        String input = inputTv.getText().trim();

        if (inputTv.isEmpty()){
            outputTv.setText("输入内容不能为空");
            return;
        }

        if (mSelectPath.isEmpty()){
            outputTv.setText("请选择需要的系统签名！");
            return;
        }

        String jar = mLocalPath + "/signapk.jar";
        String pem = mLocalPath+mSelectPath+"/platform.x509.pem";
        String pk8 = mLocalPath+mSelectPath+"/platform.pk8";
        String dstApk = input.replace(".apk","_sign.apk");

        final String signCommon = "cmd /c java -jar \""+jar+"\" \""+pem+"\" \""+pk8+"\" \""+input+"\" \""+dstApk+"\"";
        System.out.println(signCommon);

        String res = new WindowCmdCtrl().exec(signCommon);
        System.out.println(res);
        if (res.trim().isEmpty()){

            openExplorer(dstApk);

            outputTv.setText("签名成功，生成路径为："+dstApk);
        }else{
            outputTv.setText(res);
        }
    }

    private void openExplorer(String file) {
        try {
            Runtime.getRuntime().exec("explorer.exe /select,\"" +file+"\"");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void initTv(AnchorPane root) {
        inputTv.setPrefHeight(90);
        inputTv.setFont(Font.font(15));
        inputTv.setWrapText(true);//自动换行

        inputTv.setHint("点击选择APK文件或拖动APK文件进文本框");

        AnchorPane.setTopAnchor(inputTv,30.0);
        AnchorPane.setRightAnchor(inputTv,120.0);
        AnchorPane.setLeftAnchor(inputTv,10.0);

        inputTv.setOnDragExited(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                List<File> files = event.getDragboard().getFiles();
                if (files!=null&&!files.isEmpty()) {
                    String path = files.get(0).getAbsolutePath();

                    if (path.endsWith(".apk")) {
                        inputTv.setText(path);
                    } else {
                        outputTv.setText("仅支持.apk后缀的文件");
                    }
                }
            }
        });

        inputTv.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                FileChooser chooser = new FileChooser();
                chooser.setTitle("请选择要打开的文件");//不可设置
                chooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("APK文件","*.apk"));

                if (!inputTv.isEmpty()){
                    chooser.setInitialDirectory(new File(inputTv.getText()).getParentFile());
                }

                File file = chooser.showOpenDialog(new Stage());
                //如果不选文件直接关闭窗口的话，返回值为空
                if(file != null){
                    if (file.getName().endsWith(".apk")){
                        inputTv.setText(file.getAbsolutePath());
                    }else{
                        outputTv.setText("仅支持.apk后缀的文件");
                    }
                }
            }
        });


        mChoiceBox.setPrefWidth(100);
        mChoiceBox.setMaxWidth(100);
        mChoiceBox.getItems().addAll(mChoiceList);

        mChoiceBox.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue!=null&&!newValue.isEmpty()){
                mSelectPath = newValue;
            }
        });

        AnchorPane.setTopAnchor(mChoiceBox,45.0);
        AnchorPane.setRightAnchor(mChoiceBox,10.0);

        outputTv.setFont(Font.font(18));
        outputTv.setWrapText(true);
        outputTv.setPrefHeight(60);
        outputTv.setEditable(false);

        AnchorPane.setTopAnchor(outputTv,155.0);
        AnchorPane.setRightAnchor(outputTv,10.0);
        AnchorPane.setLeftAnchor(outputTv,10.0);
        AnchorPane.setBottomAnchor(outputTv,20.0);

        mVersionLabel.setWrapText(true);
        mVersionLabel.setPrefHeight(10);
        AnchorPane.setRightAnchor(mVersionLabel,10.0);
        AnchorPane.setBottomAnchor(mVersionLabel,2.0);

        root.getChildren().addAll(inputTv,outputTv, mVersionLabel, mChoiceBox);
    }

    public static void main(String[] args) {
        launch();
    }
}
